package com.vehicle.common.web.utils;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.NoSuchBeanDefinitionException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

import java.util.Map;

/**
 * Created by yantingbin on 2017/7/12.
 */
public class SpringContextHelper implements ApplicationContextAware {
    private static ApplicationContext applicationContext;

    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        SpringContextHelper.applicationContext = applicationContext;
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) throws BeansException {
        try {
            return applicationContext.getBean(name);
        } catch (BeansException e) {
            throw new RuntimeException("obtain an exception by name bean", e);
        }
    }

    public static <T> T getBean(String beanName, Class<T> clazz) {
        try {
            return applicationContext.getBean(beanName, clazz);
        } catch (BeansException e) {
            throw new RuntimeException("obtain an exception by name and clazz bean", e);
        }
    }

    public static <T> T getBean(Class<T> clazz) {
        try {
            T t = null;
            Map<String, T> map = applicationContext.getBeansOfType(clazz);
            for (Map.Entry<String, T> entry : map.entrySet()) {
                t = entry.getValue();
            }
            return t;
        } catch (BeansException e) {
            throw new RuntimeException("obtain an exception by clazz", e);
        }
    }

    public static boolean containsBean(String beanName) {
        try {
            return applicationContext.containsBean(beanName);
        } catch (Exception e) {
            throw new RuntimeException("the beans get an exception when the containsBean method is called", e);
        }
    }

    public static boolean isSingleton(String beanName) {
        try {
            return applicationContext.isSingleton(beanName);
        } catch (NoSuchBeanDefinitionException e) {
            throw new RuntimeException("the beans get an exception when the isSingleton is called", e);
        }
    }

    public static Class getType(String beanName){
        try {
            return applicationContext.getType(beanName);
        } catch (NoSuchBeanDefinitionException e) {
            throw new RuntimeException("the beans get an exception when the getType method is called",e);
        }
    }
}
